package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.MemberRespVo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.utils.HttpClientUtilUse;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 * @author wfjytd
 * @create 2022-01-04 19:10
 */
@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gittee(@RequestParam String code, HttpSession session){
        Map<String, String> map = new HashMap<String, String>();
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("client_id","a5e56762a3c9b644b510fce121e84cf0018042797f201ad3611696c9afd8a9f2");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/gitee/success");
        map.put("client_secret","9a97c37ff1a7ce07382a6f10f8f6deb95be21ce313b937a4403abcfe5743857c");
        //1.根据code换取accessToken
        String sendHttpPost = HttpClientUtilUse.getInstance().sendHttpPost("https://gitee.com/oauth/token", map);
        boolean error = sendHttpPost.contains("error");
        if (!error){
            SocialUser socialUser = JSON.parseObject(sendHttpPost, SocialUser.class);
            System.out.println(socialUser);
            //知道是哪个社交用户
            //1.当前用户如果是第一次进入网站，就注册进来
            R oauthlogin = memberFeignService.oauthlogin(socialUser);
            if (oauthlogin.getCode()==0){
                MemberRespVo data = oauthlogin.getData("data", new TypeReference<MemberRespVo>() {
                });
                session.setAttribute("loginUser",data);
                System.out.println(data);
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }

        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
